let board = [];
let mines = [];
let rows, cols, totalMines;
let gameOver = false;
let timer = 0;
let timerInterval;
let mineCount;
let firstClick = true;
let records = {
    easy: Infinity,
    medium: Infinity,
    hard: Infinity
};

function loadRecords() {
    const saved = localStorage.getItem('minesweeperRecords');
    if (saved) {
        records = JSON.parse(saved);
    }
    updateRecordDisplay();
}

function saveRecord(difficulty, time) {
    if (time < records[difficulty]) {
        records[difficulty] = time;
        localStorage.setItem('minesweeperRecords', JSON.stringify(records));
        updateRecordDisplay();
        return true;
    }
    return false;
}

function updateRecordDisplay() {
    const difficulty = document.getElementById('difficulty').value;
    const record = records[difficulty];
    document.getElementById('currentRecord').textContent = 
        record === Infinity ? '-' : `${record}秒`;
}

function updateDifficultyLabel() {
    const difficulty = document.getElementById('difficulty').value;
    const labels = {
        easy: '简单模式',
        medium: '中级模式',
        hard: '高级模式'
    };
    document.getElementById('currentDifficulty').textContent = labels[difficulty];
}

function initGame() {
    const difficulty = document.getElementById('difficulty').value;
    switch(difficulty) {
        case 'easy':
            rows = 9; cols = 9; totalMines = 10;
            break;
        case 'medium':
            rows = 16; cols = 16; totalMines = 40;
            break;
        case 'hard':
            rows = 16; cols = 30; totalMines = 99;
            break;
    }
    
    createBoard();
    renderBoard();
    startTimer();
    updateMineCount();
    firstClick = true;
    updateDifficultyLabel();
    updateRecordDisplay();
}

function createBoard() {
    board = [];
    mines = [];
    gameOver = false;
    
    for(let i = 0; i < rows; i++) {
        board[i] = [];
        for(let j = 0; j < cols; j++) {
            board[i][j] = {
                revealed: false,
                isMine: false,
                flagged: false,
                neighborMines: 0
            };
        }
    }
}

function placeMines(firstRow, firstCol) {
    let minesPlaced = 0;
    while(minesPlaced < totalMines) {
        const row = Math.floor(Math.random() * rows);
        const col = Math.floor(Math.random() * cols);
        
        if(!board[row][col].isMine && 
           (row !== firstRow || col !== firstCol) &&
           (Math.abs(row - firstRow) > 1 || Math.abs(col - firstCol) > 1)) {
            board[row][col].isMine = true;
            mines.push({row, col});
            minesPlaced++;
        }
    }
    
    calculateNeighborMines();
}

function calculateNeighborMines() {
    for(let i = 0; i < rows; i++) {
        for(let j = 0; j < cols; j++) {
            if(!board[i][j].isMine) {
                let count = 0;
                for(let di = -1; di <= 1; di++) {
                    for(let dj = -1; dj <= 1; dj++) {
                        const ni = i + di;
                        const nj = j + dj;
                        if(ni >= 0 && ni < rows && nj >= 0 && nj < cols && board[ni][nj].isMine) {
                            count++;
                        }
                    }
                }
                board[i][j].neighborMines = count;
            }
        }
    }
}

function renderBoard() {
    const boardElement = document.getElementById('board');
    boardElement.innerHTML = '';
    
    for(let i = 0; i < rows; i++) {
        const row = document.createElement('div');
        row.className = 'row';
        
        for(let j = 0; j < cols; j++) {
            const cell = document.createElement('div');
            cell.className = 'cell';
            
            if(board[i][j].revealed) {
                cell.classList.add('revealed');
                if(board[i][j].isMine) {
                    cell.classList.add('mine');
                    cell.textContent = '💣';
                } else if(board[i][j].neighborMines > 0) {
                    cell.textContent = board[i][j].neighborMines;
                    cell.classList.add(`number-${board[i][j].neighborMines}`);
                }
            } else if(board[i][j].flagged) {
                cell.classList.add('flag');
                cell.textContent = '🚩';
            }
            
            cell.addEventListener('click', () => reveal(i, j));
            cell.addEventListener('contextmenu', (e) => {
                e.preventDefault();
                flag(i, j);
            });
            cell.addEventListener('dblclick', () => revealNeighbors(i, j));
            
            row.appendChild(cell);
        }
        
        boardElement.appendChild(row);
    }
}

function reveal(row, col) {
    if(gameOver || board[row][col].flagged || board[row][col].revealed) return;
    
    if(firstClick) {
        placeMines(row, col);
        firstClick = false;
    }
    
    board[row][col].revealed = true;
    
    if(board[row][col].isMine) {
        gameOver = true;
        revealAllMines();
        showGameOver(false);
        return;
    }
    
    if(board[row][col].neighborMines === 0) {
        revealEmptyCells(row, col);
    }
    
    if(checkWin()) {
        gameOver = true;
        const isNewRecord = saveRecord(document.getElementById('difficulty').value, timer);
        showGameOver(true, isNewRecord);
    }
    
    renderBoard();
}

function revealEmptyCells(row, col) {
    for(let di = -1; di <= 1; di++) {
        for(let dj = -1; dj <= 1; dj++) {
            const ni = row + di;
            const nj = col + dj;
            if(ni >= 0 && ni < rows && nj >= 0 && nj < cols && 
               !board[ni][nj].revealed && !board[ni][nj].flagged) {
                board[ni][nj].revealed = true;
                if(board[ni][nj].neighborMines === 0) {
                    revealEmptyCells(ni, nj);
                }
            }
        }
    }
}
function flag(row, col) {
    if(!board[row][col].revealed) {
        board[row][col].flagged = !board[row][col].flagged;
        renderBoard();
        updateMineCount();
    }
}

function revealNeighbors(row, col) {
    if(!board[row][col].revealed || board[row][col].neighborMines === 0) return;
    
    let flagCount = 0;
    for(let di = -1; di <= 1; di++) {
        for(let dj = -1; dj <= 1; dj++) {
            const ni = row + di;
            const nj = col + dj;
            if(ni >= 0 && ni < rows && nj >= 0 && nj < cols && board[ni][nj].flagged) {
                flagCount++;
            }
        }
    }
    
    if(flagCount === board[row][col].neighborMines) {
        for(let di = -1; di <= 1; di++) {
            for(let dj = -1; dj <= 1; dj++) {
                const ni = row + di;
                const nj = col + dj;
                if(ni >= 0 && ni < rows && nj >= 0 && nj < cols && !board[ni][nj].flagged) {
                    reveal(ni, nj);
                }
            }
        }
    }
}

function revealAllMines() {
    mines.forEach(mine => {
        board[mine.row][mine.col].revealed = true;
    });
    renderBoard();
}

function checkWin() {
    for(let i = 0; i < rows; i++) {
        for(let j = 0; j < cols; j++) {
            if(!board[i][j].isMine && !board[i][j].revealed) {
                return false;
            }
        }
    }
    return true;
}

function startTimer() {
    clearInterval(timerInterval);
    timer = 0;
    document.getElementById('timer').textContent = timer;
    timerInterval = setInterval(() => {
        timer++;
        document.getElementById('timer').textContent = timer;
    }, 1000);
}

function updateMineCount() {
    let flaggedCount = 0;
    for(let i = 0; i < rows; i++) {
        for(let j = 0; j < cols; j++) {
            if(board[i][j].flagged) flaggedCount++;
        }
    }
    mineCount = totalMines - flaggedCount;
    document.getElementById('mineCount').textContent = mineCount;
}

function showGameOver(won, isNewRecord) {
    clearInterval(timerInterval);
    const message = document.createElement('div');
    message.className = 'game-over';
    if(won) {
        message.innerHTML = `
            <h2>🎉 恭喜获胜! 🎉</h2>
            <p>用时: ${timer}秒</p>
            ${isNewRecord ? '<p>🏆 新纪录!</p>' : ''}
        `;
    } else {
        message.innerHTML = `
            <h2>💥 游戏结束 💥</h2>
            <p>再接再厉!</p>
        `;
    }
    document.body.appendChild(message);
    setTimeout(() => message.remove(), 3000);
}

// 键盘快捷键
document.addEventListener('keydown', e => {
    if(e.key === 'r' || e.key === 'R') {
        initGame();
    }
});

// 难度切换监听
document.getElementById('difficulty').addEventListener('change', () => {
    initGame();
});

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    loadRecords();
    initGame();
});